package cool.zhoujie.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import cool.zhoujie.Constant;

/**
 * 操作歌曲对象的
 */
public class DBUtil {

    public static SQLiteDatabase db;

    public static MyDBOpenHelper dbOpenHelper;

    public static void initDB(Context context) {
        dbOpenHelper = new MyDBOpenHelper(context);
        db = dbOpenHelper.getWritableDatabase();
    }

    /**
     * 将对象添加到数据库中
     * @param recentPlay 要添加的行数据对象
     */
    public static void insert(RecentPlay recentPlay) {
        ContentValues values = new ContentValues();
        values.put("songName", recentPlay.songName);
        values.put("artistName", recentPlay.artistName);
        values.put("songPic", recentPlay.songPic);
        values.put("songPath", recentPlay.songPath);
        db.insert("music_table", null, values);
        Log.d(Constant.TAG_DB, "数据插入成功");
    }

    /**
     * 删除库中的一个指定对象
     * @param recentPlay 要删除的对象
     */
    public static void delete(RecentPlay recentPlay) {
        String songName = recentPlay.songName;
        String artistName = recentPlay.artistName;
        //delete from music where songName = "江南" and artistName = "林俊杰";
        String sql = "delete from music_table where songName = " + "\"" + songName + "\"" + " and artistName = " + "\"" + artistName + "\"";
        db.execSQL(sql);
        Log.d(Constant.TAG_NET, "数据删除成功");
    }

    /**
     * 查询表中所有数据
     * @return 所有行数据集合
     */
    public static List<RecentPlay> queryAll() {
        List<RecentPlay> recentPlayList = new ArrayList<>();
        Cursor cursor = db.query("music_table", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                RecentPlay recentPlay = new RecentPlay();
                recentPlay.songName = cursor.getString(cursor.getColumnIndex("songName"));
                recentPlay.artistName = cursor.getString(cursor.getColumnIndex("artistName"));
                recentPlay.songPic = cursor.getString(cursor.getColumnIndex("songPic"));
                recentPlay.songPath = cursor.getString(cursor.getColumnIndex("songPath"));
                recentPlayList.add(recentPlay);
            } while (cursor.moveToNext());
        }
        cursor.close();
        Log.d(Constant.TAG_NET, "查询所有数据成功");
        return recentPlayList;
    }
}
